package com.tinem.platform.web.auth.config.handler;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.tinem.platform.module.pojo.co.GatewayHeadName;
import com.tinem.platform.module.starter.sdk.MessageCode;
import com.tinem.platform.web.auth.page.LoginUserInfo;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;

/**
 * @author fzh
 * @version v1
 * @program: platform-maven-archetype
 * @className JsonAuthenticationSuccessHandler
 * @description TODO
 * @site https://fengzhihao.xyz/
 * @company
 * @create 2021-01-10 14:20
 */
@Service
public class JsonAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        if(StrUtil.isBlank(request.getParameter("ajax"))){
            response.sendRedirect("/index.do");
            return;
        }
        response.setContentType("application/json");
        response.setHeader(GatewayHeadName.X_PLATFORM_RES_CODE, MessageCode.SUCCESS.name());
        response.setHeader(GatewayHeadName.X_PLATFORM_RES_MESSAGE, MessageCode.SUCCESS.getMessage(Locale.ENGLISH));

        LoginUserInfo userDetails = (LoginUserInfo) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        response.getWriter().println(JSON.toJSONString(userDetails));
        response.getWriter().flush();
        response.getWriter().close();
    }
}
